#!/usr/bin/env python3
"""
AI试卷生成器后端启动脚本
"""
import uvicorn
import os
import sys
from pathlib import Path
from dotenv import load_dotenv

def test_dependencies():
    """测试依赖是否正确安装"""
    try:
        from langchain_community.llms import Tongyi
        from langchain_core.prompts import PromptTemplate
        from fastapi import FastAPI
        from docx import Document
        return True
    except ImportError as e:
        print(f"❌ 依赖测试失败: {e}")
        print("请运行: pip install -r requirements.txt")
        return False

def check_local_knowledge_base():
    """检查本地知识库状态"""
    knowledge_path = Path(__file__).parent / "knowledge"
    if knowledge_path.exists():
        txt_files = list(knowledge_path.glob("*.txt"))
        if txt_files:
            print(f"📚 本地知识库: 已启用 ({len(txt_files)} 个文件)")
            for txt_file in txt_files:
                print(f"   - {txt_file.name}")
            return True
        else:
            print("📚 本地知识库: 已启用 (但无txt文件)")
            return True
    else:
        print("📚 本地知识库: 未启用 (knowledge目录不存在)")
        return False

def check_bailian_knowledge_base():
    """检查阿里百炼知识库状态"""
    access_key_id = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
    access_key_secret = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    workspace_id = os.getenv("WORKSPACE_ID")
    knowledge_base_id = os.getenv("BAILIAN_KNOWLEDGE_BASE_ID")
    
    if access_key_id and access_key_secret and workspace_id and knowledge_base_id:
        print("☁️  阿里百炼知识库: 已启用")
        print(f"   工作空间ID: {workspace_id}")
        print(f"   知识库ID: {knowledge_base_id}")
        return True
    elif access_key_id or access_key_secret or workspace_id or knowledge_base_id:
        print("☁️  阿里百炼知识库: 配置不完整")
        if not access_key_id:
            print("   缺少: ALIBABA_CLOUD_ACCESS_KEY_ID")
        if not access_key_secret:
            print("   缺少: ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        if not workspace_id:
            print("   缺少: WORKSPACE_ID")
        if not knowledge_base_id:
            print("   缺少: BAILIAN_KNOWLEDGE_BASE_ID")
        return False
    else:
        print("☁️  阿里百炼知识库: 未启用")
        return False

def main():
    """主启动函数"""
    # 设置环境变量
    os.environ.setdefault("PYTHONPATH", str(Path(__file__).parent))
    
    # 加载 .env 文件
    env_path = Path(__file__).parent / ".env"
    if env_path.exists():
        load_dotenv(env_path)
        print("✅ 已加载 .env 文件")
    else:
        print("⚠️  未找到 .env 文件")
    
    # 测试依赖
    print("🔍 正在检查依赖...")
    if not test_dependencies():
        print("❌ 依赖检查失败，无法启动服务")
        sys.exit(1)
    print("✅ 依赖检查通过")
    print()
    
    # 检查知识库状态
    print("🔍 正在检查知识库...")
    local_knowledge_enabled = check_local_knowledge_base()
    bailian_knowledge_enabled = check_bailian_knowledge_base()
    print()
    
    # 检查必要的环境变量
    api_key = os.getenv("DASHSCOPE_API_KEY")
    if not api_key:
        print("⚠️  警告: 未设置 DASHSCOPE_API_KEY 环境变量")
        print("请先设置阿里云DashScope API密钥:")
        print("Windows: set DASHSCOPE_API_KEY=your_api_key")
        print("Linux/Mac: export DASHSCOPE_API_KEY=your_api_key")
        print()
        
        # 交互式设置API密钥
        try:
            api_key_input = input("请输入您的DashScope API密钥（回车跳过）: ").strip()
            if api_key_input:
                os.environ["DASHSCOPE_API_KEY"] = api_key_input
                print("✅ API密钥已临时设置")
                api_key = api_key_input
            else:
                print("❌ 未设置API密钥，服务启动后将无法调用大模型")
                confirm = input("是否继续启动？(y/n): ").strip().lower()
                if confirm != 'y':
                    print("已取消启动")
                    sys.exit(0)
        except KeyboardInterrupt:
            print("\n已取消启动")
            sys.exit(0)
        print()
    
    # 显示RAG功能状态
    if api_key and (local_knowledge_enabled or bailian_knowledge_enabled):
        if bailian_knowledge_enabled:
            print("✨ RAG功能: 已启用 (阿里百炼云知识库)")
        elif local_knowledge_enabled:
            print("✨ RAG功能: 已启用 (本地知识库)")
    elif api_key:
        print("✨ RAG功能: 未启用 (缺少知识库配置)")
    else:
        print("✨ RAG功能: 未启用 (缺少API密钥)")
    print()
    
    # 启动参数
    host = os.getenv("HOST", "0.0.0.0")
    port = int(os.getenv("PORT", 8000))
    reload = os.getenv("RELOAD", "true").lower() == "true"
    log_level = os.getenv("LOG_LEVEL", "info")
    
    print(f"🚀 启动AI试卷生成器后端服务...")
    print(f"📍 地址: http://{host}:{port}")
    print(f"📚 文档: http://{host}:{port}/docs")
    print(f"🔄 热重载: {'开启' if reload else '关闭'}")
    print("=" * 50)
    
    # 启动服务
    try:
        uvicorn.run(
            "main:app",
            host=host,
            port=port,
            reload=reload,
            log_level=log_level,
            access_log=True
        )
    except KeyboardInterrupt:
        print("\n👋 服务已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()